package com.cochain.ftp;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * @title: FtpClientPool
 * @Description: ftp客户端池
 * @Author Lmm
 * @Date: 2024/3/28 14:42
 * @Version 1.0
 */
@Slf4j
@Data
public class FtpClientPool{
    /**
     * ftp客户端连接池
     */
    private final GenericObjectPool<FTPClient> ftpClientPool;
    private final FtpClientFactory ftpClientFactory;
    private final String flag;

    /**
     * @param ftpClientFactory ftp工厂
     */
    public FtpClientPool(FtpClientFactory ftpClientFactory,String flag){
        this(ftpClientFactory.getFtpProperties().getMaxClientLimit(), ftpClientFactory,flag);
    }

    public FtpClientPool(int poolSize, FtpClientFactory factory,String flag) {
        this.ftpClientFactory = factory;
        GenericObjectPoolConfig<FTPClient> poolConfig = initPoolConfig(poolSize);
        this.ftpClientPool = new GenericObjectPool<>(factory,poolConfig);
        this.flag = flag;
    }


    public FtpClientPool(FtpClientFactory factory,GenericObjectPoolConfig<FTPClient> poolConfig,String flag) {
        this.flag = flag;
        this.ftpClientFactory = factory;
        this.ftpClientPool = new GenericObjectPool<>(factory,poolConfig);
    }

    private GenericObjectPoolConfig<FTPClient> initPoolConfig(int poolSize) {
        GenericObjectPoolConfig<FTPClient> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(poolSize);
        return poolConfig;
    }


    /**
     * 获取连接
     *
     * @return FTPClient
     */
    public FTPClient borrowObject() throws Exception {
        return ftpClientPool.borrowObject();
    }
    /**
     *
     * 归还连接
     **/
    public void returnObject(FTPClient client) {
        if (null != client)
            ftpClientPool.returnObject(client);
    }

}

